<template>
      <div>
        <bfe-dialog :title="type === 'add' ? $t('stm.btn.add') : type === 'edit' ? $t('stm.btn.edit') : $t('stm.btn.detail')" :visible.sync="showFlag" :close-on-click-modal="false" @close="handCancel">
          <div>
            <CaseTitle title="stm.roleMaintenance.roleInfo" style="margin: -10px 0 6px;" />
            <bfe-form ref="formObj" v-loading="loading" class="container" :rules="formRules" :model="formObj" label-position="top" label-width="100px">
              <div class="row">
                <!-- 所屬銀行 -->
                <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
                  <bfe-form-item :label="$t('stm.roleMaintenance.instno')" prop="bankId">
                    <bfe-select v-model="formObj.bankId" size="small" :placeholder="$t('stm.validateTip.pleaseSelect')" :disabled="type !== 'add'||authBankNo!=='0'">
                      <bfe-option v-for="(item, index) in bankList" :key="item.key" :label="item.value" :value="item.key" />
                    </bfe-select>
                  </bfe-form-item>
                </div>
                <!-- 角色编号 -->
                <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
                  <bfe-form-item :label="$t('stm.roleMaintenance.roleNo')" prop="roleNo">
                    <bfe-input v-model="formObj.roleNo" type="input" :maxlength="5" :disabled="type !== 'add'" :placeholder="$t('stm.validateTip.pleaseInput')" size="small" />
                  </bfe-form-item>
                </div>
                <!-- 角色名稱 -->
                <div class="col-xs-12 col-sm-4 col-md-4 col-lg-4">
                  <bfe-form-item :label="$t('stm.roleMaintenance.rolename')" prop="roleName">
                    <bfe-input v-model="formObj.roleName" type="input" :maxlength="50" :placeholder="$t('stm.validateTip.pleaseInput')" :disabled="type === 'detail'" size="small" />
                  </bfe-form-item>
                </div>
                <!-- 描述 -->
                <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
                  <bfe-form-item :label="$t('stm.roleMaintenance.description')" prop="roleDesc">
                    <bfe-input v-model="formObj.roleDesc" type="textarea" :maxlength="100" :col="2" :placeholder="$t('stm.validateTip.pleaseInput')" :disabled="type === 'detail'" size="small" />
                  </bfe-form-item>
                </div>
              </div>
            </bfe-form>
            <CaseTitle title="stm.roleMaintenance.roleFun" style="margin-top: -16px;" />
            <div class="handBtn">
              <bfe-button type="text" :icon="`arrow-${btnDirection}`" style="padding-left: 16px;" @click="foldTree">
                {{ $t(buttonName[btnDirection]) }}
              </bfe-button>
            </div>
            <bfe-tree
              v-if="showFlag"
              ref="tree"
              :data="treeData[language]"
              show-checkbox
              node-key="id"
              :loading="loading"
              :default-checked-keys="checkIdList"
              :props="defaultProps"
            />
          </div>
          <span slot="footer" class="dialog-footer">
            <bfe-button @click="handCancel">{{ $t('stm.btn.cancel') }}</bfe-button>
            <bfe-button v-if="type !== 'add'" type="primary" :loading="loading" @click="optLogInquiry">{{ $t('stm.userMaintenance.optLogInquiry') }}</bfe-button>
            <bfe-button v-if="type !== 'detail'" type="primary" :loading="loading" @click="handConfirm">{{ $t('stm.btn.confirm') }}</bfe-button>
          </span>
        </bfe-dialog>
        <OperateLog ref="operateLog" />
      </div>
    </template>
    
    <script>
    import CaseTitle from '@stm/components/CaseTitle'
    import {mapState} from 'vuex'
    import OperateLog from './OperateLog'
        
    export default {
      components: {
        CaseTitle,
        OperateLog
      },
      props: {
        bankList: {
          type: Array,
          default: () => {}
        },
        authBankNo: {
          type: String,
          default: () => {}
        },
      },
      data() {
        return {
          showFlag: false,
          formRules: {
            bankId: [{ required: true, message: this.$t('stm.validateTip.pleaseSelect'), trigger: 'blur' }],
            roleNo: [{ required: true, message: this.$t('stm.validateTip.pleaseInput'), trigger: 'blur' }],
            roleName: [{ required: true, message: this.$t('stm.validateTip.pleaseInput'), trigger: 'blur' }],
            roleDesc: [{ required: true, message: this.$t('stm.validateTip.pleaseInput'), trigger: 'blur' }],
          },
          formObj: {},
          type: '',
          loading: false,
          treeData: {
            zh_TW: [],
            en_US: []
          },
          defaultProps: {
            children: 'children',
            label: 'text'
          },
          btnDirection: 'down',
          buttonName: {
            up: 'stm.roleMaintenance.up',
            down: 'stm.roleMaintenance.down'
          },
          expanded: false,
          checkIdList: [],
          type: '', 
          pageData: {}
        }
      },
      computed: {
        ...mapState({
          language: (state) => state.base.language
        })
      },
      methods: {
        getMap(list,type) {
          _.flatMap(list, node => {
            node.disabled =type==='detail'? true:false;
            if (node.children) {
              this.getMap(node.children);
            }
            return node;
          });
          return list;
        },
        initPage(type, row){
          this.type = type
          this.showFlag = true
          console.log(this.bankList,'=====add')
          if(this.bankList.length===1){
            this.formObj.bankId=this.bankList[0].key
          }
          console.log(this.authBankNo)
          if(type !== 'add'){
            this.pageData = {
              ...row
            }
            this.getPageData()
          }
          this.getMenuList()
        },
        optLogInquiry(){
          const {roleNo, bankId, bankIdDesc} = this.formObj
          this.$refs.operateLog.initPage({roleNo, bankId, bankName: bankIdDesc})
        },
        handCancel(){
          this.expanded = false
          this.btnDirection = 'down'
          this.formObj = {}
          this.checkIdList = []
          this.pageData = {}
          this.$refs.formObj.resetFields()
          this.showFlag = false
        },
        handConfirm(){
          this.$refs.formObj.validate(ok => {
            if(ok){   
              this.loading = true                 
              const checkedNodes = this.$refs.tree.getCheckedNodes()
              const checkedHalfNodes = this.$refs.tree.getHalfCheckedNodes()
              console.log(checkedNodes, 'checkedNodes===')
              const list = checkedNodes.map(item => {
                return {
                  menuNo: item.id,
                  checked: true,
                  indeterminate: false,                 
                }
              })
              const listHalf = checkedHalfNodes.map(item => {
                return {
                  menuNo: item.id,
                  checked: true,
                  indeterminate: true,                      
                }
              })
              const params = {
                optCode: this.type === 'add' ? 'STM005ADD1101' : 'STM005MOD1101',
                payload: {
                  roleInfo: this.formObj,
                  menuBoList: [...list, ...listHalf]
                }
              }
              this.$p2svr(this.$api['_01_STM005ROLE1100'] , 'RequestPoAuth', params).then(res => {
                if(res.optMsgInfo && res.optMsgInfo.optStatus === 'success'){
                  this.handCancel()
                  this.$emit('doSearch')
                }
              }).finally(() => {
                this.loading = false
              })
            }
          })
        },
        foldTree(){
          this.btnDirection = this.btnDirection === 'up' ? 'down' : 'up'
          this.expanded = !this.expanded
          const nodes = this.$refs.tree.store._getAllNodes();
          nodes.forEach(item => {
            item.expanded = this.expanded
          })
        },
        getMenuList(){
          this.loading = true
          const {bankId, roleNo} = this.pageData
          const params = {
            optCode: 'STM005GET1103',
            payload: {
              menuNo: '0001.A129.0000',
              isNeedBtn: '1',
              roleNo,
              bankId,
            }
          }
          this.$p2svr(this.$api['_01_STM005ROLE1100'] , 'RequestPoAuth', params).then(res => {
            this.treeData = {
              zh_TW: this.getMap(_.result(res, 'payload.zhTree'),this.type),
              en_US: _.result(res, 'payload.enTree')
            }
            this.checkIdList = _.result(res, 'payload.checkIdList')
          }).finally(() => {
            this.loading = false
          })
        },
        getPageData(){
          const {bankId, roleNo} = this.pageData
          const params = {
            optCode: 'STM005GET1102',
            payload: {
              bankId,
              roleNo
            }
          }
          this.$p2svr(this.$api['_01_STM005ROLE1100'] , 'RequestPoAuth', params).then(res => {
            this.formObj = res.payload || {}
    
          }).finally(() => {
            this.loading = false
          })
        }
      }
    }
    </script>
    
    <style lang="less" scoped>
    /deep/.giop-dialog--small{
        width: 50% !important;
        margin-left: -25% !important;
        max-height: 70vh;
    }
    /deep/.giop-dialog__body {
        max-height: calc(70vh - 99px);
    }
    /deep/.giop-tree{
        width: 100%;
        border: none;
        float: left;
    }
    .handBtn{
        width: 100%;
        float: left;
        text-align: right;
        margin-top: -34px;
    }
    </style>